import React, { Component } from 'react'
import LeftAside from './component/LeftAside'
import RightAside from './component/RightAside'
import Middle from './component/Middle'
import './ReleaseExam.less'
import { message } from 'antd'
import { getCookie } from '@/utils/cookie/cookie'
import { insertExam, insertExamPaper, insertQuestion } from '@/services/exam'
import { connect } from 'dva'

const mapStateToProps = (state) => {
    return state["updateExam"]
}
const mapDispatchToProps = (dispatch) => {
    return {
        change(field, data) {
            dispatch({
                type: 'updateExam/change',
                field, data
            })
        }
    }
}
class ReleaseExam extends Component {

    constructor(props) {
        super(props)
        this.state = {
            baseInfo: {},
            questionList: [],
            fullScore: 0,
            loading: false,
            exam_paper_id: `${new Date().getTime()}`,
            exam_id: `${new Date().getTime()}`
        }
    }

    componentDidUpdate() {
        console.log(this.props)
    }

    checkBaseInfo(baseInfo) {
        let flag = true
        const { title, time, classId, passScore } = baseInfo
        const { fullScore } = this.state
        if (!title?.trim?.()) {
            flag = false
            message.warn("考试标题未填写")
        }
        if (time) {
            if (!time.startTime || !time.endTime) {
                flag = false
                message.warn("考试时间未选择")
            }
        } else {
            flag = false
            message.warn("考试时间未选择")
        }
        if (!(classId instanceof Array && classId.length > 0)) {
            flag = false
            message.warn("班级未选择")
        }
        if (fullScore) {
            if (isNaN(fullScore)) {
                flag = false
                message.warn("分数有误")
            } else {
                if (fullScore < 0) {
                    flag = false
                    message.warn("分数有误")
                } else {
                    if (passScore) {
                        if (isNaN(passScore)) {
                            flag = false
                            message.warn("分数有误")
                        } else {
                            if (passScore > fullScore) {
                                flag = false
                                message.warn("分数有误")
                            }
                        }
                    } else {
                        flag = false
                        message.warn("分数有误")
                    }
                }
            }
        } else {
            flag = false
            message.warn("分数有误")
        }
        return flag
    }

    async preInsert(questionList, baseInfo) {
        this.setState({
            loading: true
        })
        const { title, time, classId, passScore } = baseInfo
        const { fullScore } = this.state
        let exam = {}
        let examPaper = {}
        let nextQuestionList = []
        const exam_paper_id = this.state.exam_paper_id
        let question_id_list = questionList.map((q) => {
            return q.id
        })
        question_id_list = question_id_list.join(",")
        let question_score_list = questionList.map((q) => {
            return q.score
        })
        question_score_list = question_score_list.join(",")
        exam = {
            exam_id: this.state.exam_id,
            exam_title: title,
            start_time: time.startTime,
            end_time: time.endTime,
            teach_id: getCookie("userId"),
            class_id: classId.join(','),
            exam_status: 'notStart',
            exam_paper_id,
            max_score: fullScore,
            pass_score: passScore,
            deleted: 0
        }
        examPaper = {
            exam_paper_id,
            question_id_list,
            question_score_list,
            deleted: 0
        }
        nextQuestionList = questionList.map((q) => {
            const { id, type, questionContext, trueAnswer, options } = q
            let strTrueAnswer = trueAnswer
            if (trueAnswer instanceof Array) {
                strTrueAnswer = trueAnswer.join("-$$&&$$-")
            }
            return {
                question_id: id || null,
                question_type: type || null,
                question_context: questionContext || null,
                true_answer: `${strTrueAnswer}`,
                options: options?.join?.("-$$&&$$-") || null,
                deleted: 0
            }
        })

        const r1 = await insertQuestion(nextQuestionList)
        const r2 = await insertExamPaper(examPaper)
        const r3 = await insertExam(exam)
        if (r1.status === 0 && r2.status === 0 && r3.status === 0) {
            message.success("操作完成")
            location.reload();
        } else {
            message.success("操作失败")
        }
        this.setState({
            loading: false
        })
    }

    render() {
        const { isUpdate, baseInfo, questionList } = this.props
        return <div className='release-exam'>
            <LeftAside
                baseInfo={isUpdate ? baseInfo : undefined}
                fullScore={this.state.fullScore} onMessage={(values) => {
                    this.setState({
                        baseInfo: values
                    })
                }} />
            <Middle
                questionList={isUpdate ? questionList : undefined}
                getFullScore={(fullScore) => {
                    this.setState({
                        fullScore,
                    })
                }} onRelease={(questionList) => {
                    if (this.checkBaseInfo(this.state.baseInfo)) {
                        this.preInsert(questionList, this.state.baseInfo)
                    }
                }} loading={this.state.loading} />
            {/* <RightAside onAdd={(value) => {
                console.log(value)
            }} /> */}
        </div>
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(ReleaseExam)